package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.UserLoginMapper;
import com.heima.admin.service.UserLoginService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.search.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserLoginServiceImpl extends ServiceImpl<UserLoginMapper, AdUser> implements UserLoginService {
    @Override
    public ResponseResult login(AdUserDto dto) {
        //判断参数
        if (dto.getName()==null||dto.getPassword()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //根据用户名查找用户
        String name = dto.getName();
        AdUser adUser = this.getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, name));
        //判断是否能从数据库中查询用户，查不到则返回   你输入的用户名不存在
        if (adUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"你输入的用户名不存在");
        }
        //从数据库查询到的用户中获取盐的信息
        String salt = adUser.getSalt();

        //将盐于前端传来的密码组合并用md5进行加密与数据库中的密码相比较
        String password = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
//        String password = MD5Utils.encodeWithSalt(dto.getPassword(), salt);
        if (password.equals(adUser.getPassword())){
            //用AppJwtUtil工具类获取token
            String token = AppJwtUtil.getToken(adUser.getId().longValue());
            Map<String,Object> map =new HashMap();

            //将密码和盐等私密信息清空
            adUser.setPassword("");
            adUser.setSalt("");

            //将adUser和token信息返回给前端
            map.put("user",adUser);
           map.put("token",token);
           return ResponseResult.okResult(map);
        }
        //密码错误返回密码错误信息
        return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
    }
}
